#include "calculator.h"
#include "ui_calculator.h"
#include <QPushButton>
#include <QDebug>
#include <cmath>

Calculator::Calculator(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Calculator)
{
    ui->setupUi(this);

    resetCalculator();

    // 数字按钮 (0-9)连接
    for (int i = 0; i < 10; ++i) {
        QString buttonName = "btn" + QString::number(i);
        QPushButton *button = findChild<QPushButton*>(buttonName);
        if (button) {
            connect(button, &QPushButton::clicked, this, &Calculator::digitClicked);
        }
    }

    // 运算符按钮连接
    connect(findChild<QPushButton*>("btnPlus"), &QPushButton::clicked, this, &Calculator::plusClicked);
    connect(findChild<QPushButton*>("btnMinus"), &QPushButton::clicked, this, &Calculator::minusClicked);
    connect(findChild<QPushButton*>("btnMultiply"), &QPushButton::clicked, this, &Calculator::multiplyClicked);
    connect(findChild<QPushButton*>("btnDivide"), &QPushButton::clicked, this, &Calculator::divideClicked);
    connect(findChild<QPushButton*>("btnEquals"), &QPushButton::clicked, this, &Calculator::equalsClicked);

    // 运算符号按钮连接
    connect(findChild<QPushButton*>("btnDecimal"), &QPushButton::clicked, this, &Calculator::decimalClicked);
    connect(findChild<QPushButton*>("btnSign"), &QPushButton::clicked, this, &Calculator::signClicked);
    connect(findChild<QPushButton*>("btnClear"), &QPushButton::clicked, this, &Calculator::clearClicked);
    connect(findChild<QPushButton*>("btnClearAll"), &QPushButton::clicked, this, &Calculator::clearAllClicked);
    connect(findChild<QPushButton*>("btnReciprocal"), &QPushButton::clicked, this, &Calculator::reciprocalClicked);
    connect(findChild<QPushButton*>("btnSquare"), &QPushButton::clicked, this, &Calculator::squareClicked);

    setDisplay(currentValue);
}

Calculator::~Calculator()
{
    delete ui;
}

bool firstDivision;
void Calculator::resetCalculator()
{
    currentValue = 0.0;
    storedValue = 1.0;
    currentOperation.clear();
    waitingForOperand = true;
    hasDecimal = false;
    firstDivision = true; // 首次除法的标志
}

void Calculator::digitClicked()
{
    QPushButton *clickedButton = qobject_cast<QPushButton *>(sender());
    int digitValue = clickedButton->text().toInt();

    if (waitingForOperand) {
        currentValue = digitValue;
        waitingForOperand = false;
        hasDecimal = false;
    } else {
        if (hasDecimal) {
            // 处理小数
            QString currentText = ui->display->text();
            if (!currentText.contains('.')) {
                currentText += '.';
            }
            currentText += QString::number(digitValue);
            currentValue = currentText.toDouble();
        } else {
            currentValue = currentValue * 10 + digitValue;
        }
    }

    setDisplay(currentValue);
}

void Calculator::plusClicked()
{
    if (!waitingForOperand) {
        calculate(currentValue, "+");
    }
    currentOperation = "+";
    waitingForOperand = true;
}

void Calculator::minusClicked()
{
    if (!waitingForOperand) {
        calculate(currentValue, "-");
    }
    currentOperation = "-";
    waitingForOperand = true;
}

void Calculator::multiplyClicked()
{
    if (!waitingForOperand) {
        calculate(currentValue, "×");
    }
    currentOperation = "×";
        waitingForOperand = true;
}

void Calculator::divideClicked()
{
        if (firstDivision) {
        storedValue = currentValue;
        firstDivision = false;     // 标记不再为第一次执行除法
        } else {
        if (!waitingForOperand) {
            calculate(currentValue, "÷");
        }
        }
        currentOperation = "÷";
            waitingForOperand = true;
}

void Calculator::equalsClicked()
{
    if (!currentOperation.isEmpty() && !waitingForOperand) {
        calculate(currentValue, currentOperation);
        currentOperation.clear();
    }
    waitingForOperand = true;
}

void Calculator::clearClicked()
{
    currentValue = 0.0;
    storedValue = 0.0; // 和clearAllClicked类似，重置storedValue
    currentOperation.clear();
    waitingForOperand = true;
    hasDecimal = false;
    setDisplay(currentValue);
}

void Calculator::clearAllClicked()
{
    resetCalculator();
    setDisplay(currentValue);
}

void Calculator::signClicked()
{
    currentValue = -currentValue;
    setDisplay(currentValue);
}

void Calculator::decimalClicked()
{
    if (waitingForOperand) {
        currentValue = 0.0;
        waitingForOperand = false;
    }

    if (!hasDecimal) {
        QString currentText = ui->display->text();
        if (!currentText.contains('.')) {
            currentText += '.';
            ui->display->setText(currentText);
        }
        hasDecimal = true;
    }
}

void Calculator::reciprocalClicked()
{
    if (currentValue == 0.0) {
        abortOperation();
        return;
    }

    currentValue = 1.0 / currentValue;
    setDisplay(currentValue);
    waitingForOperand = true;
    hasDecimal = false;
}

void Calculator::squareClicked()
{
    currentValue = currentValue * currentValue;
    setDisplay(currentValue);
    waitingForOperand = true;
    hasDecimal = false;
}

void Calculator::calculate(double operand, const QString &operation)
{
    if (operation == "+") {
        storedValue += operand;
    } else if (operation == "-") {
        storedValue -= operand;
    } else if (operation == "×") {
        storedValue *= operand;
} else if (operation == "÷")
    {
        if (operand == 0.0) {
            abortOperation();
            return;
        }
        storedValue =storedValue / operand;
    }
    else
    {
        storedValue = operand;
    }

    currentValue = storedValue;
    setDisplay(currentValue);
}

void Calculator::abortOperation()
{
    resetCalculator();
    ui->display->setText("Error");
}

void Calculator::setDisplay(double value)
{
    // 避免科学计数法显示
    if (qAbs(value) < 1e10 && qAbs(value) > 1e-5 || value == 0.0) {
        QString text = QString::number(value, 'f', 10);

        // 移除末尾多余的0和小数点
        if (text.contains('.')) {
            while (text.endsWith('0')) {
                text.chop(1);
            }
            if (text.endsWith('.')) {
                text.chop(1);
            }
        }
        ui->display->setText(text);
    } else {
        // 对于非常大或非常小的数，使用科学计数法
        ui->display->setText(QString::number(value, 'g', 10));
    }
}
